package com.jdk.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CGLibProxy {

    public static Object getClassProxy(Class obj){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(obj);
        enhancer.setCallback(new ClassMethodInterceptor());
        return enhancer.create();
    }
    public static Object getInterfaceClassProxy(Class obj){
        Enhancer enhancer = new Enhancer();
        enhancer.setInterfaces(new Class[]{obj});
        enhancer.setCallback(new InterfaceMethodInterceptor(new XiaoMing()));
        return enhancer.create();
    }
}

class ClassMethodInterceptor implements MethodInterceptor{

    public void before(){

    }
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("CGLIB.........ClassMethodInterceptor");
        return methodProxy.invokeSuper(o, objects);
    }

    public void after(){

    }
}

class InterfaceMethodInterceptor implements MethodInterceptor{
    private Person person;

    public InterfaceMethodInterceptor(Person person) {
        this.person = person;
    }

    public void before(){

    }
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("CGLIB.........InterfaceMethodInterceptor");
        return methodProxy.invoke(person, objects);
    }

    public void after(){

    }
}
